import React from 'react'
import {
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons'
import * as Icon from '@ant-design/icons'

import { useNavigate } from 'react-router-dom'
import { selectMenuList } from '../../store/reducers/tab'

import { useDispatch } from 'react-redux'

import MenuConfig from '../../config/index'

import { Layout, Menu } from 'antd'
const { Sider } = Layout

// 动态获取icon
const iconToElement = (name) => React.createElement(Icon[name])

// 处理菜单数据
const items = MenuConfig.map(pItem => {
  // 没有子菜单
  const child = {
    key: pItem.path,
    icon: iconToElement(pItem.icon),
    label: pItem.label
  }
  // 有子菜单
  if (pItem.children) {
    child.children = pItem.children.map(cItem => {
      return {
        key: cItem.path,
        label: cItem.label
      }
    })
  }
  return child
})

const CommonAside = (props) => {
  const navigate = useNavigate()
  const dispatch = useDispatch()

  // 添加数据到store
  const setTabList = (val) => {
    dispatch(selectMenuList(val))
  }

  // 菜单跳转
  const handleMenu = (e) => {
    let data
    MenuConfig.forEach(item => {
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item;
        // 如果有二级菜单
        if (e.keyPath.length > 1) {
          data = item.children.find(child => {
            return child.path == e.key
          })
        }
      }
    })
    setTabList({
      ...data
    })
    navigate(e.key)
  }

  return (
    <Sider
      trigger={null}
      collapsible
      collapsed={props.collapsed}
      style={{ height: '100vh' }}
    >
      <h3 className="logo">{props.collapsed ? '后台' : '后台管理系统'}</h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={['1']}
        items={items}
        onClick={handleMenu}
      />
    </Sider>
  )
}

export default CommonAside
